# -*- coding = utf-8 -*-
import cv2 as cv
import os
import numpy as np

FILE = ''
ROW = 5
COLUMN = 40

ADD_DATA = ''
ADD_TEMP = './new_template/'
ADD_ROI = ''

kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
black = np.ones((36, 30, 1), dtype=np.uint8)
mask = black.copy()
mask[3:33, 2:28] = 255


def pic_horizon(file_dir):
	files = os.listdir(file_dir)
	img_files = []
	imgs = []
	for file in files:
		photo = cv.imread(file_dir + file, cv.IMREAD_GRAYSCALE)
		photo = cv.resize(photo, (30, 30))
		img_files.append(photo)
	for x in range(0, 200, 40):
		for i in range(40):
			img = img_files[x + i]
		line = cv.hconcat(img_files[x:x + 40])
		imgs.append(line)
	num = cv.vconcat(imgs)
	cv.imshow("result", num)
	cv.waitKey(0)
	return num


def resize(image, width=None, height=None, inter=cv.INTER_AREA):
	dim = None
	(h, w) = image.shape[:2]
	if width is None and height is None:
		return image
	if width is None:
		r = height / float(h)
		dim = (int(w * r), height)
	else:
		r = width / float(w)
		dim = (width, int(h * r))
	resized = cv.resize(image, dim, interpolation=inter)
	return resized


def MakeTemplate(cnt=1):
	# files = os.listdir(ADD_DATA)
	# mask = cv.threshold(mask, 0, 255, cv.THRESH_BINARY)
	for x in range(1, 9):
		FILE = './' + str(x) + '/'
		files = os.listdir(FILE)
		length = len(files)
		if length > 400:
			length = 400
		for i in range(length):
			black_c = black.copy()
			cnt += 1
			print(FILE + files[i])
			photo = cv.imread(FILE + files[i])
			resized = cv.resize(photo, (30, 36))
			gray = cv.cvtColor(resized, cv.COLOR_BGR2GRAY)
			_, thresh = cv.threshold(gray, 100, 255, cv.THRESH_BINARY_INV)
			res = cv.bitwise_and(thresh, mask)
			cnts, _ = cv.findContours(res, cv.INTER_LINEAR, cv.CHAIN_APPROX_NONE)
			for cnt in cnts:
				if cv.contourArea(cnt) > 40:
					cv.drawContours(black_c, cnt, -1, (255, 0, 0), -1)  # 不要在原图上面画，-1是所有的轮廓
					# blur = cv.GaussianBlur(thresh, (3, 3), 1)
					# dilate = cv.dilate(black_c, kernel)
					# erode = cv.erode(dilate, kernel)
					# dilate_2 = cv.dilate(black_c, kernel)
					# erode_2 = cv.erode(dilate, kernel)
					# open = cv.morphologyEx(black_c, cv.MORPH_OPEN, kernel)
					close = cv.morphologyEx(black_c, cv.MORPH_CLOSE, kernel, iterations=2)
					# top = cv.morphologyEx(black_c, cv.MORPH_TOPHAT, kernel)
					# hat = cv.morphologyEx(black_c, cv.MORPH_BLACKHAT, kernel)

			# h = cv.hconcat([gray, thresh, blur, res, dilate, erode, dilate_2, erode_2, open, close, top, hat])
			# cv.imshow("h", h)
			if cv.waitKey(0) == ord('q'):
				break
			# cv.imwrite(ADD_TEMP + str(cnt) + '.jpg', thresh)
			cv.imwrite(ADD_TEMP + str(x) + '_' + str(2 * i + 1) + '.jpg', res)
			cv.imwrite(ADD_TEMP + str(x) + '_' + str(2 * i) + '.jpg', close)
			print(i, "cvt over")


def Matcher(img):
	resized = cv.resize(img, (30, 36))
	cv.imshow("show", resized)
	gray = cv.cvtColor(resized, cv.COLOR_BGR2GRAY)
	_, thresh = cv.threshold(gray, 0, 255, cv.THRESH_OTSU)
	# cv.imshow("thresh", thresh)
	# cv.waitKey()
	# print(gray.shape)
	# temps = os.listdir('/make/')
	temps = os.listdir('make/')
	scores = []
	for j in range(5):
		score = 0
		for i in range(10):
			temp = './make/' + temps[j * 10 + i]
			template = cv.imread(temp, cv.IMREAD_GRAYSCALE)
			# print(type(template), type(gray))
			dst = cv.bitwise_and(template, gray)
			height, width = dst.shape
			for x in range(width):
				for y in range(height):
					if (dst[y][x] == gray[y][x]) > 0:
						score += 1
		scores.append((j + 1, score))
	print(scores)


# MakeTemplate()
pic_l = []
for i in range(8):
	v = pic_horizon('trained_numbers/' + str(i + 1) + '/')
	pic_l.append(v)
result = cv.vconcat(pic_l)
cv.imwrite("digits.jpg", result)
# image = cv.imread("1.jpg")
'''
temps = os.listdir('make/')
for i in range(len(temps)):
    temp = './make/' + temps[i]
    template = cv.imread(temp)#, cv.IMREAD_GRAYSCALE)
    Matcher(img=template)
'''